<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form @submit="loginFn">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLode"
          :disabled="isLode"
          loading-text="登陆中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'login',
  data() {
    return {
      isLode: false,
      mobile: '13245678912',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '请填写用户名' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async loginFn() {
      // const res = await userLogin({
      //   code: this.code,
      //   mobile: this.mobile
      // })
      // console.log(res)
      this.isLode = true
      try {
        const res = await userLogin(this.mobile, this.code)
        console.log(res)
        this.$toast.success('登陆成功')
        this.setToken(res.data)
        // this.$store.commit('user/setToken', res.data)
        // 跳转到首页
        // this.$router.push('/')
        // 判读有无back路径
        const back = this.$route.query.back
        console.log(back)
        // 判断是否有flag(标识)
        console.log(this.$route.query.flag)
        if (this.$route.query.flag) {
          // console.log(this.$router.back())
          return this.$router.back()
        }
        if (back) {
          this.$router.push(back)
        } else {
          this.$router.push('/')
        }
      } catch {
        this.$toast.fail('登陆失败')
      }
      this.isLode = false
    }
  }
}
</script>

<style></style>
